//
//  MainPageViewController.m
//  ZhuanZuBao
//
//  Created by 戴伟 on 2020/8/28.
//  Copyright © 2020 戴伟. All rights reserved.
//

#import "MainPageViewController.h"
#import "RentCell.h"
#import "SDCycleScrollView.h"
#import "RentListViewController.h"
#import "CitysViewController.h"
#import "RentDetailViewController.h"
#import "RentModel.h"
#import "ShareViewController.h"

@interface MainPageViewController ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate,  CLLocationManagerDelegate, AMapLocationManagerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *shareImageView;

@property (nonatomic, assign) NSInteger page;

@property (strong, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *navView;
@property (nonatomic, strong) SDCycleScrollView *bannerView;
@property (weak, nonatomic) IBOutlet UIButton *cityBtn;
@property (nonatomic, copy) NSString *city;
@property (nonatomic, strong) UIScrollView *menuView;
@property (nonatomic, strong) UIButton *selectedBtn;
@property (nonatomic, strong) NSMutableArray *menuArr;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (strong, nonatomic) IBOutlet UIView *footerView;

@property (nonatomic, strong) UIView *linewView;

@property (nonatomic, strong) AMapLocationManager *locationManager;

@end

@implementation MainPageViewController

- (BOOL)fd_prefersNavigationBarHidden{
    return YES;
}

-(AMapLocationManager *)locationManager{
    if (!_locationManager) {
        _locationManager = [[AMapLocationManager alloc] init];
        _locationManager.delegate = self;
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
        _locationManager.locationTimeout =2;
        _locationManager.reGeocodeTimeout = 2;
    }
    return _locationManager;
}

-(NSMutableArray *)menuArr{
    if (!_menuArr) {
        _menuArr = [NSMutableArray array];
    }
    return _menuArr;
}
-(NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    _page = 1;
    [_navView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(SafeAreaTopHeight);
    }];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        if (self.city && self.city.length > 0) {
            [self getData];
        }else{
            //重新定位
            [self location];
        }
        
    }];
    self.tableView.separatorColor = SEPARATECOLOR;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.tableHeaderView = self.headerView;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.page ++;
        [self getData];
    }];
    
    _bannerView = [[SDCycleScrollView alloc] init];
    _bannerView.backgroundColor = BGCOLOR;
    [_headerView addSubview:_bannerView];
    [_bannerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(12);
        make.right.mas_offset(-12);
        make.top.mas_offset(10);
        make.height.mas_equalTo((DEVICE_SCREEN_WIDTH-24)*0.344);
    }];
    _bannerView.layer.cornerRadius = 4;
    _bannerView.layer.shadowOffset = CGSizeMake(1, 1);
    _bannerView.layer.shadowOpacity = 0.6;
    _bannerView.layer.shadowColor = [UIColor lightGrayColor].CGColor;
    

    _shareImageView.layer.shadowOffset = CGSizeMake(1, 1);
    _shareImageView.layer.shadowOpacity = 0.6;
    _shareImageView.layer.shadowColor = [UIColor lightGrayColor].CGColor;
    _shareImageView.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(share)];
    [_shareImageView addGestureRecognizer:tap];
    
    CGFloat headerH = SafeAreaTopHeight+(DEVICE_SCREEN_WIDTH-24)*(0.344+0.3)+120;
    _headerView.frame = CGRectMake(0, 0, DEVICE_SCREEN_WIDTH, headerH);
    
    _menuView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, headerH-44, DEVICE_SCREEN_WIDTH, 44)];
    [_headerView addSubview:_menuView];
    _menuView.backgroundColor = [UIColor whiteColor];
    
    [self getBanner];
    
    //用户明确拒绝，可以弹窗提示用户到设置中手动打开权限
//    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
//        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"无法获取您的地理位置" message:@"由于系统的限制，APP需要获取地理位置权限，才能正常使用" preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *action = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
//        }];
//        [alert addAction:action];
//        [self presentViewController:alert animated:YES completion:nil];
//    }
//    else{
//        CLLocationManager *cllocation = [[CLLocationManager alloc] init];
//        cllocation.delegate = self;
//        if(![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined){
//            //弹框提示用户是否开启位置权限
//            [cllocation requestWhenInUseAuthorization];
//        }else{
//
//        }
//    }
    [self location];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self checkUpdate];
    });
}

-(void)location{
    [MBProgressHUD showMessag:@"定位中" toView:self.view];
    
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if (error){
                NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
                
                if (error.code == AMapLocationErrorLocateFailed){
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"无法获取您的地理位置" message:@"APP需要获取地理位置权限，才能正常使用,请在设置中为转租宝打开权限。" preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                    }];
                    [alert addAction:action1];
                    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"继续使用" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        NSString *cityName = @"南京";
                        CGFloat width = [cityName sizeWithMyFont:[UIFont systemFontOfSize:14]].width;
                        [self.cityBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                            make.width.mas_equalTo(width+36);
                        }];
                        [self.cityBtn setTitle:cityName forState:UIControlStateNormal];
                        self.city = cityName;
                        [User sharedUser].currentCity = cityName;
                        self.page = 1;
                        [MBProgressHUD showMessag:@"" toView:self.view];
                        [self getMenu];
                    }];
                    [alert addAction:action2];
                    [self presentViewController:alert animated:YES completion:nil];
                }else{
                    [MBProgressHUD showError:@"定位失败" toView:nil];
                }
                

            }else{
                if (regeocode){
                    NSString *city = regeocode.city;
                    if (!city) {
                        city = @"未知地区";
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"当前区域未开通租房服务，请您点击左上角的位置按钮，选择中国大陆地区。" message:@"" preferredStyle:UIAlertControllerStyleAlert];
                        UIAlertAction *action = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:nil];
                        [alert addAction:action];
                        [self presentViewController:alert animated:YES completion:nil];
                    }
                    if ([city hasSuffix:@"市"]) {
                        city = [city substringToIndex:city.length-1];
                    }
                    [User sharedUser].currentCity = city;
                    self.city = city;
                    CGFloat width = [city sizeWithMyFont:[UIFont systemFontOfSize:14]].width;
                    [self.cityBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.width.mas_equalTo(width+36);
                    }];
                    [self.cityBtn setTitle:city forState:UIControlStateNormal];
                    [self getMenu];
                }
            }
            
        }];
}

- (void)amapLocationManager:(AMapLocationManager *)manager doRequireLocationAuth:(CLLocationManager*)locationManager{
    [locationManager requestAlwaysAuthorization];
}
-(void)getBanner{
    NSDictionary *dict = @{
        @"pge":@(_page),
        @"cnt":@"10"
    };
    [NetWork sendGetUrl:@"index/banner.php" withParams:dict success:^(id responseBody) {
        NSLog(@"%@", responseBody);
        NSArray *arr = responseBody[@"lst"];
        NSMutableArray *img = [NSMutableArray array];
        for (NSDictionary *dict in arr) {
            [img addObject:dict[@"img"]];
        }
        self.bannerView.imageURLStringsGroup = img;
    } failure:^(NSError *error) {
        
    }];
}

-(void)getMenu{
    NSDictionary *dict = @{
        @"pid":@"26",
        @"pge":@"1",
        @"cnt":@"10"
    };
    [NetWork sendGetUrl:@"fy/fy_lm.php" withParams:dict success:^(id responseBody) {
        NSLog(@"%@", responseBody);
        [self.menuArr addObjectsFromArray:responseBody[@"lst"]];
        [self setupUI];
    } failure:^(NSError *error) {
        
    }];
}

-(void)setupUI{
    CGFloat width = 0;
    for (NSInteger i = 0; i< _menuArr.count; i++) {
        NSDictionary *dict = _menuArr[i];
        NSString *title = dict[@"nme"];
        CGFloat btnW = [title sizeWithMyFont:[UIFont systemFontOfSize:15 weight:UIFontWeightMedium] constrainedToSize:CGSizeMake(200, 44)].width+20;
        
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(width, 0, btnW, 44)];
        [btn setTitle:dict[@"nme"] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightMedium];
        if (i == 0) {
            [btn setTitleColor:THEMECOLOR forState:UIControlStateNormal];
            _selectedBtn = btn;
            _linewView = [[UIView alloc] initWithFrame:CGRectMake((btnW-30)/2, 40, 30, 2)];
            _linewView.backgroundColor = THEMECOLOR;
            [btn addSubview:_linewView];
        }else{
            [btn setTitleColor:BLACKTEXTCOLOR forState:UIControlStateNormal];
        }
        btn.tag = i;
        [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [_menuView addSubview:btn];
        width += btnW;
    }
    
    _menuView.contentSize = CGSizeMake(width, 44);
    [self getData];
}

-(void)getData{

    NSDictionary *menuDict  = _menuArr[_selectedBtn.tag];
    NSDictionary *dict = @{
        @"pge": @(_page),
        @"cnt":@"10",
        @"tags":  menuDict[@"nme"],
        @"city": _city
    };
    [NetWork sendGetUrl:@"fy/fy_lst.php" withParams:dict success:^(id responseBody) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSArray *arr = [RentModel mj_objectArrayWithKeyValuesArray:responseBody[@"lst"]];

        if (self.page == 1) {
            [self.dataArr removeAllObjects];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer resetNoMoreData];
        }else{
            [self.tableView.mj_header endRefreshing];
            if (arr.count == 0) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [self.tableView.mj_footer endRefreshing];
            }
        }
        [self.dataArr addObjectsFromArray:arr];
        if (self.dataArr.count) {
            self.tableView.tableFooterView = [UIView new];
        }else{
            self.tableView.tableFooterView = self.footerView;
        }
        [self.tableView reloadData];
        
        if (self.dataArr.count) {
            self.tableView.tableFooterView = [UIView new];
        }else{
            self.tableView.tableFooterView = self.footerView;
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 110;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RentModel *rent = _dataArr[indexPath.row];
    RentCell *cell = [RentCell cellWithTableView:tableView];
    cell.rent = rent;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([User isGuest]) {
        LoginViewController *vc = [LoginViewController new];
        BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:vc];
        nav.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [self presentViewController:nav animated:YES completion:nil];
        return;
    }
    RentModel *rent = _dataArr[indexPath.row];
    RentDetailViewController *vc = [[RentDetailViewController alloc] initWithRentId:rent.rentId];
    [self.navigationController pushViewController:vc animated:YES];
}


- (IBAction)rentList:(UIButton *)sender {
    if (!_city) {
        [MBProgressHUD showWarning:@"正在定位" toView:nil];
        return;
    }
    RentListViewController *vc = [[RentListViewController alloc] initWithType:sender.tag];
    vc.city = self.city;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)chooseCity:(id)sender {
    CitysViewController *vc = [CitysViewController new];
    vc.chooseCityBlock = ^(NSString * _Nonnull cityName) {
        CGFloat width = [cityName sizeWithMyFont:[UIFont systemFontOfSize:14]].width;
        [self.cityBtn mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(width+36);
        }];
        [self.cityBtn setTitle:cityName forState:UIControlStateNormal];
        self.city = cityName;
        [User sharedUser].currentCity = cityName;
        self.page = 1;
        [MBProgressHUD showMessag:@"" toView:self.view];
        [self getData];
    };
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - 更改分类
-(void)btnClicked:(UIButton *)btn{
    [_selectedBtn setTitleColor:BLACKTEXTCOLOR forState:UIControlStateNormal];
    _selectedBtn = btn;
    [_selectedBtn setTitleColor:THEMECOLOR forState:UIControlStateNormal];
    _linewView.frame = CGRectMake((btn.width-24)/2, _linewView.y, _linewView.width, _linewView.height);
    [_selectedBtn addSubview:_linewView];
    self.page = 1;
    [MBProgressHUD showMessag:@"" toView:self.view];
    [self getData];
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (!_city) {
        [MBProgressHUD showWarning:@"正在定位" toView:nil];
        return NO;
    }
    RentListViewController *vc = [[RentListViewController alloc] initWithType:0];
    vc.city = _city;
    [self.navigationController pushViewController:vc animated:YES];
    return NO;
}

-(void)share{
    ShareViewController *vc = [ShareViewController new];
    vc.link = @"http://share.cdlife.vip/zzb/index.html";
    vc.shareTitle = @"转租宝";
    vc.shareDesc = @"转租宝APP-最新版下载链接，欢迎下载，海量房源等你来看！";
    vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:vc animated:NO completion:nil];
}

-(void)checkUpdate{
    [NetWork sendGetUrl:@"user/get_bbh.php" withParams:nil success:^(id responseBody) {
        NSString *onlineVersion = responseBody[@"ios"];
        NSString *key = @"CFBundleShortVersionString";
        NSString *currentVersion = [NSBundle mainBundle].infoDictionary[key];
        if ([NSString hasUpdateonLineVersion:onlineVersion currentVersion:currentVersion]) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"发现新版本!" message:@"请您将APP更新至最新版本" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"去更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSString *reviewURL = @"itms-apps://itunes.apple.com/app/id1530756161";
                NSURL *url = [NSURL URLWithString:reviewURL];
                UIApplication *application = [UIApplication sharedApplication];
                if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
                    [application openURL:url options:@{} completionHandler:^(BOOL success) {
                        
                    }];
                } else {
                    [application openURL:url];
                }
            }];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }
    } failure:^(NSError *error) {
        
    }];
}

@end
